import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useCart = defineStore('cart',()=>{
  // status
  const cart = ref(JSON.parse(uni.getStorageSync('cart') || '[]'))
  // 方法
  const addToCart = (goods)=>{
    // 先查找购物车中是否有这个商品
    const findResult = cart.value.find(x=>x.goods_id === goods.goods_id)
    if(!findResult){
      cart.value.push(goods)
    }else{
      findResult.goods_count++
    }
    saveToStorage()
  }
  // 持久化存储
  const saveToStorage = ()=>{
    uni.setStorageSync('cart',JSON.stringify(cart.value))
  }
  // 更新购物车中商品的勾选状态
  const updateGoodsState =(goods)=>{
    const findResult = cart.value.find(x=>x.goods_id === goods.goods_id)
    if(findResult){
      findResult.goods_state = goods.goods_state
      saveToStorage()
    }
  }
  // 更新商品数量
  const updateGoodsCount = (goods)=>{
    const findResult = cart.value.find(x=>x.goods_id === goods.goods_id)
    if(findResult){
      findResult.goods_count = goods.goods_count
      saveToStorage()
    }
  }
  // 根据id删除对应的商品
  const removeGoodsById = (goods_id)=>{
    cart.value = cart.value.filter(x=>x.goods_id !== goods_id)
    saveToStorage()
  }
  // 更新所有商品的勾选状态
  const updateAllGoodsState = (newState)=>{
    cart.value.forEach(x=>x.goods_state = newState)
    saveToStorage()
  }
  // 计算属性
  // 购物车中所有商品的总数量
  const total = computed(()=>{
    return cart.value.reduce((sum,item)=>sum+item.goods_count,0)
  })
  // 已勾选的商品总数量
  const checkedCount = computed(()=>{
    return cart.value.filter(x => x.goods_state).reduce((total,item)=>total+item.goods_count,0)
  })
  // 计算已勾选商品的总价格
  const checkedGoodsAmount = computed(()=>{
    return cart.value.filter(x=>x.goods_state).reduce((total,item)=>total+item.goods_count*item.goods_price,0).toFixed(2)
  })
  return {
    cart,
    total,
    addToCart,
    updateGoodsState,
    updateGoodsCount,
    removeGoodsById,
    checkedCount,
    updateAllGoodsState,
    checkedGoodsAmount
  }
}
)